package com.ustcinfo.study.hive.r4.wangqiangqiang;

import java.sql.*;

/**
 * Describe:  hive连接，并执行HiveSql
 * Author:wangqiangqiang
 */
public class HiveConnection {
    // hive链接地址
    private static String url = "jdbc:hive2://192.168.153.100:10000/default";
    // hive 驱动
    private static String driver = "org.apache.hive.jdbc.HiveDriver";
    //hive用户名
    private static String userName = "wang";
    // hive密码
    private static String passwd = "";

    private static Connection connection = null;
    private static Statement statement = null;
    private static ResultSet resultSet = null;

    public static void main(String[] args) throws SQLException {
       //  加载hive驱动
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            System.out.println("驱动加载失败");
            e.printStackTrace();
        }

        try {
            // 连接hive
            connection = DriverManager.getConnection(url, userName, passwd);
            if (connection != null) {
                System.out.println("hive 连接成功");
            } else {
                System.out.println("hive 连接失败");
            }

            statement = connection.createStatement();
            
            //获取域名相同的ip个数
           String sql="select domain_name,count(*) as count from dnssample group by domain_name";
            //String sql="select domain_name ,count(1) as count from dnssample order by domain_name";
            // 获取数据库中所有的表
            resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
                System.out.println("域名："+resultSet.getString(1)+","+"Ip个数："+resultSet.getString(2));
            	
            }

        } catch (SQLException e) {
            e.printStackTrace();
            System.exit(1);
        } finally {//关闭连接
        	 if (resultSet != null) {
                 resultSet.close();
             }
            if (statement != null) {
                statement.close();
            }
            if(connection != null) {
                connection.close();
            }
            
        }

    }

}
